﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace NASM_Develop_IDE
{
    class ErrorLineNumbersExtracter
    {
        private string output;
        public ErrorLineNumbersExtracter(string output)
        {
            this.output = output;
        }
        public Dictionary<int, string> GetLineNumbers()
        {
            try
            {
                Regex pathRegex = new Regex(@".*\.(asm)");
                Dictionary<int, string> lineNumbers = new Dictionary<int, string>();
                Regex numberRegex = new Regex(@"^\d+$");
                List<string> errorLines = output.Replace("\r", "").Split('\n').ToList();
                errorLines.ForEach(delegate(string errorLine)
                {
                    if (errorLine != "")
                    {
                        Match pathMatch = pathRegex.Match(errorLine);
                        string path = pathMatch.Value;
                        string lineNumberStr = getLineNumberString(errorLine);
                        lineNumbers.Add(int.Parse(lineNumberStr), Path.GetFileName(path));
                        
                    }
                });

                return lineNumbers;
            }
            catch
            {
                return null;
            }
        }
        private string getLineNumberString(string line)
        {
            StringBuilder lineNumberString = new StringBuilder();
            List<char> characters =  line.ToList();
            int index = characters.FindIndex((char c) => (char.IsDigit(c)));
            lineNumberString.Append(characters[index]);
            int endIndex = characters.FindLastIndex((char c) => (char.IsDigit(c)));
            for (index += 1;  index <= endIndex; index++)
            {
                if (!char.IsDigit(characters[index]))
                {
                    return null;
                }
                else
                {
                    lineNumberString.Append(characters[index]);
                }
            }
            return lineNumberString.ToString();
        }
    }
}
